// 变量声明
let CACHE_VERSION = 1
let CACHE_NAME = `cache_v${CACHE_VERSION}`
let CACHE_URLS = [
  '/',
  '/index.html',
  '/manifest.json',
  '/assets/test.js',
  '/assets/test.css',
  '/assets/icon-96x96.png',
  '/assets/icon-144x144.png',
  '/assets/icon-192x192.png',
  // '/api/lessons',
  // '/api/lesson-detail'
]

// 缓存数据
function preCache () {
  return caches
    .open(CACHE_NAME)
    .then((cache) => {
      console.log('cache:', cache)
      return cache.addAll(CACHE_URLS)
    })
}
// 清除缓存
function clearCache () {
  return caches.keys().then(keys => {
    console.log('caches keys:', keys)
    keys.forEach(key => {
      if (key !== CACHE_NAME) {
        caches.delete(key)
      }
    })
  })
}
// 请求&缓存
function fetchAndCache (req) {
  console.log('fetchAndCache:', req)
  return fetch(req).then((res) => {
    saveToCache(req, res.clone())
    return res
  })
}
// 保存到缓存
function saveToCache (req, res) {
  return caches
    .open(CACHE_NAME)
    .then(cache => cache.put(req, res))
}

// 安装
self.addEventListener('install', (event) => {
  event.waitUntil(
    preCache().then(self.skipWaiting)
  )
})

// 即将获取所在域的控制权
self.addEventListener('activate', (event) => {
  event.waitUntil(
    Promise.all([
      self.clients.claim(),
      clearCache()
    ])
  )
})

self.addEventListener('fetch', (event) => {
  // let url = new URL(event.request.url)
  // console.log('Fetch request for:', event.request.url, url)
  // if (url.origin === self.origin) {
  //   return
  // }
  // let needCache = CACHE_URLS.some(v => event.request.url.includes(v))
  // console.log('Fetch request for:', event.request.url, needCache)
  // if (needCache) {
  //   event.respondWith(
  //     fetchAndCache(event.request).catch(() => {
  //       return caches.match(event.request)
  //     })
  //   )
  // } else {
  //   event.respondWith(
  //     fetch(event.request).catch(() => {
  //       return caches.match(event.request)
  //     })
  //   )
  // }

  // 先查询缓存，没有数据则请求网络
  event.respondWith(caches.match(event.request).catch(() => {
    return fetchAndCache(event.request)
  }))
})
